import { prisma } from '@/lib/prisma/client'
import { NextResponse } from 'next/server'

export async function GET(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { searchParams } = new URL(request.url)
    const status = searchParams.get('status')
    const timeRange = searchParams.get('timeRange')
    const search = searchParams.get('search')
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')

    // 构建查询条件
    const where: any = {
      sceneId: params.id
    }

    if (status && status !== 'ALL') {
      where.status = status
    }

    if (timeRange && timeRange !== 'ALL') {
      const now = new Date()
      const ranges = {
        TODAY: new Date(now.setHours(0,0,0,0)),
        WEEK: new Date(now.setDate(now.getDate() - 7)),
        MONTH: new Date(now.setDate(now.getDate() - 30))
      }
      where.startTime = {
        gte: ranges[timeRange as keyof typeof ranges]
      }
    }

    // 获取总记录数
    const total = await prisma.sceneHistory.count({ where })

    // 获取分页数据
    const history = await prisma.sceneHistory.findMany({
      where,
      orderBy: { startTime: 'desc' },
      skip: (page - 1) * limit,
      take: limit
    })

    return NextResponse.json({
      data: history,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      }
    })
  } catch (error) {
    return NextResponse.json(
      { error: '获取历史记录失败' },
      { status: 500 }
    )
  }
}

export async function POST(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const data = await request.json()
    const history = await prisma.sceneHistory.create({
      data: {
        sceneId: params.id,
        status: data.status,
        message: data.message,
        details: data.details
      }
    })
    return NextResponse.json(history)
  } catch (error) {
    return NextResponse.json(
      { error: '创建历史记录失败' },
      { status: 500 }
    )
  }
} 